<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\Common\Redis\TaggedCache;
use App\CustHub\Model\ChAffiliateAccount;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Config\Annotation\Value;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Mine\Abstracts\AbstractMapper;

class ChAffiliateAccountMapper extends AbstractMapper
{

    #[Value('cache.default.prefix')]
    protected string $prefix;

    public function assignModel()
    {
        $this->model = ChAffiliateAccount::class;
    }

    /**
     * 根据id查询
     * @param mixed $id
     * @return ChAffiliateAccount|Model|string|Builder|null
     */
    #[Cacheable(prefix: 'affiliate_account_info', value: '#{$id}',ttl: 15 * 60)]
    public function findById(mixed $id): Model|string|ChAffiliateAccount|Builder|null
    {
        return $this->model::query()->find($id);
    }

    /**
     * 根据主账号id和会员id查询
     * @param int $mainUid
     * @param string $memberId
     * @param int $type
     * @return ChAffiliateAccount|Model|string|Builder|null
     */
    public function findByMainUidAndMemberIdAndType(int $mainUid, string $memberId,int $type): ChAffiliateAccount|Model|string|Builder|null
    {
        $info = $this->model::query()
            ->where('main_uid', $mainUid)
            ->where('member_id', $memberId)
            ->where('type',$type)
            ->first();
        return $info;
    }

    public function handleSearch(Builder $query, array $params): Builder
    {
        $query->where('main_uid',$params['main_uid']);

        if(isset($params['type']) && $params['type']){
            $query->where('type',$params['type']);
        }

        return $query;
    }


    public function rmCache(mixed $id): void
    {
        $redis = redis();
        $keys[] = $this->prefix . 'affiliate_account_info:'.$id;
        $redis->del($keys);

        $tagKey = ChAffiliateAccount::ACCOUNT_TAG_KEY.$id;
        container()->get(TaggedCache::class)->flushTag($tagKey);
    }
}